package com.smtlive.configure;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import com.smtlive.authentication.SmtAuthenticationProvider;
import com.smtlive.domain.ActionRole;
import com.smtlive.domain.Role;
import com.smtlive.service.ActionRoleService;
import com.smtlive.service.RoleService;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private SmtAuthenticationProvider provider;// 自定义验证

	@Autowired
	RoleService roleService;

	@Autowired
	ActionRoleService actionRoleService;

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/", "/home").permitAll();
		Iterable<Role> roles = roleService.findAllRole();
		for (Role role : roles) {
			ArrayList<ActionRole> actionRoles = actionRoleService.findAction(role.getRoleId());
			String[] actions = new String[actionRoles.size()];
			int i = 0;
			for (ActionRole actionRole : actionRoles) {
				actions[i] = actionRole.getAction();
				i++;
			}
			http.authorizeRequests().antMatchers(actions).hasRole(role.getRole());
		}
		http.authorizeRequests().anyRequest().authenticated()
			.and().formLogin().loginPage("/login").permitAll()
			.and().logout().logoutSuccessUrl("/").permitAll();

	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		// 自定义验证
		auth.authenticationProvider(provider);
	}
}
